package com.work.xxzl.module.fragment;


import android.app.AlertDialog;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Pair;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.widget.EaseConversationList;
import com.work.xxzl.R;
import com.work.xxzl.adapter.CommonRecyclerViewAdapter;
import com.work.xxzl.adapter.CommonRecyclerViewHolder;
import com.work.xxzl.base.BaseFragmentForMain;
import com.work.xxzl.module.pagemessage.ChatActivity;
import com.work.xxzl.utils.LogUtils;
import com.work.xxzl.utils.UIUtils;
import com.work.xxzl.utils.ViewUtils;
import com.work.xxzl.varyview.VaryViewHelper;
import com.work.xxzl.varyview.VaryViewHelperUtils;
import com.work.xxzl.view.DividerItemDecoration;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * @author WZ 2018/12/10
 * 消息
 */
public class MessageFragment extends BaseFragmentForMain {

    @BindView(R.id.iv_add)
    ImageView ivAdd;
    @BindView(R.id.iv_messagepeople)
    ImageView ivMessagepeople;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.tv_newfriends)
    TextView tvNewfriends;
    @BindView(R.id.tv_minecare)
    TextView tvMinecare;
    @BindView(R.id.tv_lookme)
    TextView tvLookme;
    @BindView(R.id.listview)
    EaseConversationList listview;
    private VaryViewHelper mVaryViewHelper;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_message_content;
    }

    @Override
    protected void initView() {
        ViewUtils.setOnClickListeners(this, ivAdd, ivMessagepeople, tvSearch, tvNewfriends, tvMinecare, tvLookme);
    }

    @Override
    protected void initData() {
        super.initData();
        //空白页面
        mVaryViewHelper = VaryViewHelperUtils.getDefaultViewHelper(getContext(), listview, null);
        getChatList();
        //环信消息监听
        EMClient.getInstance().chatManager().addMessageListener(msgListener);
    }

    EMMessageListener msgListener = new EMMessageListener() {
        @Override
        public void onMessageReceived(List<EMMessage> list) {
            handler.sendEmptyMessage(1);
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {

        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
            //收到已读回执
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
            //收到已送达回执
        }

        @Override
        public void onMessageRecalled(List<EMMessage> messages) {
            //消息被撤回
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
            //消息状态变动
        }
    };

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: {
                    getChatList();
                }
                default:
                    break;
            }

        }
    };

    //获取聊天列表
    private void getChatList() {
        EMClient.getInstance().chatManager().loadAllConversations();
        final List<EMConversation> mEMConversationList = new ArrayList<>();
        mEMConversationList.addAll(loadConversationList());
        //初始化，参数为会话列表集合
        listview.init(mEMConversationList);
        LogUtils.d("获取聊天列表");
        if (mEMConversationList.size() > 0) {
            mVaryViewHelper.showDataView();
        } else {
            mVaryViewHelper.setUpContentView(getString(R.string.no_message), R.mipmap.ic_launcher);
            mVaryViewHelper.showEmptyView();
        }

        //刷新列表
        listview.refresh();
        listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                //删除聊天记录
                emptyHistory(mEMConversationList.get(position));
                return true;
            }
        });
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                EMConversation emConversation = mEMConversationList.get(position);
                String userName = emConversation.conversationId();
                Intent intent = new Intent();

                if (emConversation.getLastMessage().getFrom().equals("system")) {
                    //当消息类型是系统消息，点击跳转消息列表
                    //设置所有消息已读
                    emConversation.markAllMessagesAsRead();
//                    intent.setClass(getActivity(), SystemMessageActivity.class);
                } else {
                    //跳转到聊天页面
                    intent.setClass(getActivity(), ChatActivity.class);
                    try {
                        String from = emConversation.getLastMessage().getFrom();
                        String nickName = emConversation.getLastMessage().getStringAttribute("nickName");
                        String to_username = emConversation.getLastMessage().getStringAttribute("to_username", "");
                        if (from.equals(userName)) {
                            intent.putExtra(EaseConstant.nickName, nickName);
                            String imageUrl = emConversation.getLastMessage().getStringAttribute("imageUrl", "");
                            intent.putExtra(EaseConstant.imageUrl, imageUrl);
                        } else {
                            intent.putExtra(EaseConstant.nickName, to_username);
                            String imageUrl = emConversation.getLastMessage().getStringAttribute("to_headportrait", "");
                            intent.putExtra(EaseConstant.imageUrl, imageUrl);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    intent.putExtra(EaseConstant.EXTRA_USER_ID, userName);
                    intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
                }
                startActivity(intent);
            }
        });

        int number = 0;
        for (int i = 0; i < mEMConversationList.size(); i++) {
            number += mEMConversationList.get(i).getUnreadMsgCount();
        }

        Intent intent = new Intent();
        intent.setAction("android_message");
        intent.putExtra("message_number", number);
        getActivity().sendBroadcast(intent);
    }


    /**
     * load conversation list
     * 获取聊天列表
     *
     * @return +
     */
    protected List<EMConversation> loadConversationList() {
        // get all conversations
        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        /**
         * lastMsgTime will change if there is new message during sorting
         * so use synchronized to make sure timestamp of last message won't change.
         */
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                }
            }
        }
        try {
            // Internal is TimSort algorithm, has bug
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            list.add(sortItem.second);
        }
        return list;
    }

    /**
     * sort conversations according time stamp of last message
     * 聊天列表排序
     *
     * @param conversationList
     */
    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {

                if (con1.first.equals(con2.first)) {
                    return 0;
                } else if (con2.first.longValue() > con1.first.longValue()) {
                    return 1;
                } else {
                    return -1;
                }
            }

        });
    }

    /**
     * 删除此聊天记录
     */
    protected void emptyHistory(final EMConversation emConversation) {
        View popupView = getLayoutInflater().inflate(R.layout.layout_delete_message, null);
        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.dialog_style);
        final AlertDialog dialog = builder.setView(popupView).create();

        TextView msureTextView = popupView.findViewById(R.id.sure_view);
        ImageView mCancelImageView = popupView.findViewById(R.id.cancel_view);
        // 确定
        msureTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if (emConversation != null) {
                    emConversation.clearAllMessages();
                }
                getChatList();
            }
        });
        mCancelImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();

    }


    @Override
    protected void processClick(View v) {
        super.processClick(v);
        switch (v.getId()) {
            case R.id.iv_add:
                //点击加号更多
                break;
            case R.id.iv_messagepeople:
                //通讯录
                break;
            case R.id.tv_search:
                //搜索好友
                break;
            case R.id.tv_newfriends:
                //新的朋友
                break;
            case R.id.tv_minecare:
                //我关注的
                break;
            case R.id.tv_lookme:
                //联系我的
                break;
        }
    }
}
